﻿using HyEduOnline.Entities;
using HyEduOnline.Server.Admin;
using HyEduOnline.Server.Student;
using HyEduOnline.Server.Teacher;
using HyEduOnline.Server.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using HyEudOnline.Server.Common;
using Aspose.Cells;
using Aspose.Slides;

namespace WebSite.Areas.WebApi.Controllers
{
    public class CommonController : BaseController
    {
        private TeachersDAO teachersDAO = new TeachersDAO();
        private StudentsDAO studentsDAO = new StudentsDAO();
        private SysLogDAO _logDao = new SysLogDAO();

        private const string uploadFolder = "/Upload/header/temp/";//上传目标图片的位置
        private const string OrginalPath = "/Upload/header/temp1/";//剪裁后的原图

        private const string oCoursePath = "/Upload/CourseImg/large/";//课程封面大图
        private const string mCoursePath = "/Upload/CourseImg/middle/";//课程封面中图

        private const string oHeaderPath = "/Upload/header/large/";//原图缩略的大头像
        private const string mHeaderPath = "/Upload/header/middle/";//原图生成的中图
        private const string sHeaderPath = "/Upload/header/small/";//原图生成的小图


        private static string webFile;//上传文件的完整路径

        /// <summary>
        /// 头像上传
        /// </summary>
        /// <param name="qqfile"></param>
        /// <returns></returns>
        public JsonResult ProcessUpload(string qqfile)
        {
            string imgName = DateTime.Now.ToString("ddHHmmssff");//图片名称
            string imgType = qqfile.Substring(qqfile.LastIndexOf("."));//图像类型
            string uploadPath = "";
            webFile = uploadFolder + imgName + imgType;
            uploadPath = Server.MapPath(uploadFolder);//物理存储路径
            try
            {
                if (!Directory.Exists(uploadPath))
                {
                    Directory.CreateDirectory(uploadPath);
                }

                if (Request.Files.Count > 0)
                {
                    //IE
                    HttpPostedFileBase postFile = HttpContext.Request.Files[0];

                    ImageHelper.ZoomAuto(postFile, Server.MapPath(webFile), 400, 300, "", "");
                }
                else
                {
                    //chrome\firefox
                    ImageHelper.ZoomAuto(Request.InputStream, Server.MapPath(webFile), 400, 300, "", "");
                }
                return Json(new { success = true, message = webFile });
            }
            catch (Exception e)
            {
                return Json(new { fail = true, message = e.Message });
            }
        }


        /// <summary>
        ///  教师头像图像裁剪并保存       
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        public void CutTeaImage(FormCollection form)
        {
            TbSysLog tmpLog = new TbSysLog();

            string savePath = "";
            string fileNmae = "";
            //取得剪裁后的4点坐标
            int x = (int)float.Parse(form["x"]);
            int y = (int)float.Parse(form["y"]);
            int w = (int)float.Parse(form["w"]);
            int h = (int)float.Parse(form["h"]);

            //获取目标图片的相对路径
            string imgsrc = form["imgsrc"].Substring(0, form["imgsrc"].LastIndexOf("?"));

            //获取原图片的相对路径
            string oSavePath = imgsrc.Replace("/temp/", "/temp1/");
            fileNmae = Server.MapPath(OrginalPath);//物理存储路径

            if (!Directory.Exists(fileNmae))
            {
                Directory.CreateDirectory(fileNmae);
            }
            ImageHelper.SelfCropFromImage(Server.MapPath(webFile), Server.MapPath(oSavePath), x, y, w, h);//剪裁

            //缩略生成大头像
            savePath = imgsrc.Replace("/temp/", "/large/");
            fileNmae = Server.MapPath(oHeaderPath);//物理存储路径

            if (!Directory.Exists(fileNmae))
            {
                Directory.CreateDirectory(fileNmae);
            }
            ImageHelper.ZoomAuto(Server.MapPath(oSavePath), Server.MapPath(savePath), 100, 100, "", "");//等比缩放

            //更新头像，先删除原有图像

            //找到当前用户
            TbTeachers temp = teachersDAO.GetByID(frontCurrentTea.GetUserID());
            string picUrl = temp.SPicUrl;
            if (!string.IsNullOrEmpty(picUrl))
            {
                //删除大中小三个旧的头像
                string delFileName = Server.MapPath(picUrl);
                try
                {
                    System.IO.File.Delete(delFileName);

                    delFileName = Server.MapPath(temp.SPicUrl.Replace("/large/", "/middle/"));
                    System.IO.File.Delete(delFileName);

                    delFileName = Server.MapPath(temp.SPicUrl.Replace("/large/", "/small/"));
                    System.IO.File.Delete(delFileName);
                }

                catch (Exception e2)
                {
                    //将异常信息存入SysLog日志表中 by lx 2015.1.20
                    tmpLog.ILogType = 999;
                    tmpLog.SMessage = e2.Message.ToString();
                    _logDao.Insert(tmpLog);
                }
            }
            //更新数据库SPicUrl字段
            temp.SPicUrl = savePath;
            teachersDAO.Update(temp);//更新到数据库

            try
            {
                //获取 中等 图片的相对路径 60*60 
                savePath = imgsrc.Replace("/temp/", "/middle/");
                fileNmae = Server.MapPath(mHeaderPath);//物理存储路径

                if (!Directory.Exists(fileNmae))
                {
                    Directory.CreateDirectory(fileNmae);
                }
                ImageHelper.ZoomAuto(Server.MapPath(oSavePath), Server.MapPath(savePath), 60, 60, "", "");//等比缩放

                //获取 小 图片的相对路径 30*30 
                savePath = imgsrc.Replace("/temp/", "/small/");
                fileNmae = Server.MapPath(sHeaderPath);//物理存储路径

                if (!Directory.Exists(fileNmae))
                {
                    Directory.CreateDirectory(fileNmae);
                }
                ImageHelper.ZoomAuto(Server.MapPath(oSavePath), Server.MapPath(savePath), 30, 30, "", "");

            }
            catch (Exception e3)
            {
                //将异常信息存入SysLog日志表中 by lx 2015.1.20
                tmpLog.ILogType = 999;
                tmpLog.SMessage = savePath + "::::" + e3.Message.ToString();
                _logDao.Insert(tmpLog);
            }


            return;
        }


        /// <summary>
        ///  课程封面图像裁剪并保存       
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        public void CutCourseImage(FormCollection form)
        {
            TbSysLog tmpLog = new TbSysLog();
            string savePath = "";
            string fileNmae = "";
            //取得剪裁后的4点坐标
            int x = (int)float.Parse(form["x"]);
            int y = (int)float.Parse(form["y"]);
            int w = (int)float.Parse(form["w"]);
            int h = (int)float.Parse(form["h"]);
            int CourseId = int.Parse(form["CourseID"]);//获取当前课程ID

            //获取目标图片的相对路径
            string imgsrc = form["imgsrc"].Substring(0, form["imgsrc"].LastIndexOf("?"));

            //获取原图片的相对路径
            string oSavePath = imgsrc.Replace("/temp/", "/temp1/");
            fileNmae = Server.MapPath(OrginalPath);//物理存储路径

            if (!Directory.Exists(fileNmae))
            {
                Directory.CreateDirectory(fileNmae);
            }
            ImageHelper.CropFromImage(Server.MapPath(webFile), Server.MapPath(oSavePath), x, y, w, h);//剪裁

            //缩略生成大图
            savePath = imgsrc.Replace("/header/temp/", "/CourseImg/large/");
            fileNmae = Server.MapPath(oCoursePath);//物理存储路径

            if (!Directory.Exists(fileNmae))
            {
                Directory.CreateDirectory(fileNmae);
            }
            ImageHelper.ZoomAuto(Server.MapPath(oSavePath), Server.MapPath(savePath), 300, 200, "", "");//等比缩放           


            //获取 中等 图片的相对路径 200*200 
            savePath = imgsrc.Replace("/header/temp/", "/CourseImg/middle/");
            fileNmae = Server.MapPath(mCoursePath);//物理存储路径

            if (!Directory.Exists(fileNmae))
            {
                Directory.CreateDirectory(fileNmae);
            }
            ImageHelper.ZoomAuto(Server.MapPath(oSavePath), Server.MapPath(savePath), 200, 200, "", "");//等比缩放


            //找到当前课程
            TbDeanCourse temp = new DeanCourseDAO().GetByID(CourseId);
            if (!string.IsNullOrEmpty(temp.SImgUrl))//删除大中小三个旧的头像
            {
                string delFileName = Server.MapPath(temp.SImgUrl);
                try
                {
                    System.IO.File.Delete(delFileName);

                    delFileName = Server.MapPath(temp.SImgUrl.Replace("/middle/", "/large/"));
                    System.IO.File.Delete(delFileName);
                }
                catch (Exception e4)
                {
                    //将异常信息存入SysLog日志表中 by lx 2015.1.20
                    tmpLog.ILogType = 999;
                    tmpLog.SMessage = e4.Message.ToString();
                    _logDao.Insert(tmpLog);
                }

            }

            //更新数据库SPicUrl字段
            temp.SImgUrl = savePath;
            new DeanCourseDAO().Update(temp);//更新到数据库

            return;
        }



        /// <summary>
        ///  学生头像图像裁剪并保存       
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        public void CutStuImage(FormCollection form)
        {
            TbSysLog tmpLog = new TbSysLog();
            string savePath = "";
            string fileNmae = "";
            //取得剪裁后的4点坐标
            int x = (int)float.Parse(form["x"]);
            int y = (int)float.Parse(form["y"]);
            int w = (int)float.Parse(form["w"]);
            int h = (int)float.Parse(form["h"]);

            //获取目标图片的相对路径
            string imgsrc = form["imgsrc"].Substring(0, form["imgsrc"].LastIndexOf("?"));

            //获取原图片的相对路径
            string oSavePath = imgsrc.Replace("/temp/", "/temp1/");
            fileNmae = Server.MapPath(OrginalPath);//物理存储路径

            if (!Directory.Exists(fileNmae))
            {
                Directory.CreateDirectory(fileNmae);
            }
            ImageHelper.CropFromImage(Server.MapPath(webFile), Server.MapPath(oSavePath), x, y, w, h);//剪裁

            //缩略生成大头像
            savePath = imgsrc.Replace("/temp/", "/large/");
            fileNmae = Server.MapPath(oHeaderPath);//物理存储路径

            if (!Directory.Exists(fileNmae))
            {
                Directory.CreateDirectory(fileNmae);
            }
            ImageHelper.ZoomAuto(Server.MapPath(oSavePath), Server.MapPath(savePath), 100, 100, "", "");//等比缩放


            //找到当前用户
            TbStudents temp = studentsDAO.GetByID(frontCurrentStu.GetUserID());
            if (!string.IsNullOrEmpty(temp.SPicUrl))//删除大中小三个旧的头像
            {
                try
                {
                    string delFileName = Server.MapPath(temp.SPicUrl);
                    System.IO.File.Delete(delFileName);

                    delFileName = Server.MapPath(temp.SPicUrl.Replace("/large/", "/middle/"));
                    System.IO.File.Delete(delFileName);

                    delFileName = Server.MapPath(temp.SPicUrl.Replace("/large/", "/small/"));
                    System.IO.File.Delete(delFileName);
                }
                catch (Exception e5)
                {
                    //将异常信息存入SysLog日志表中 by lx 2015.1.20
                    tmpLog.ILogType = 999;
                    tmpLog.SMessage = e5.Message.ToString();
                    _logDao.Insert(tmpLog);
                }

            }


            //更新数据库SPicUrl字段
            temp.SPicUrl = savePath;
            studentsDAO.Update(temp);//更新到数据库

            try
            {
                //获取 中等 图片的相对路径 60*60 
                savePath = imgsrc.Replace("/temp/", "/middle/");
                fileNmae = Server.MapPath(mHeaderPath);//物理存储路径

                if (!Directory.Exists(fileNmae))
                {
                    Directory.CreateDirectory(fileNmae);
                }
                ImageHelper.ZoomAuto(Server.MapPath(oSavePath), Server.MapPath(savePath), 60, 60, "", "");//等比缩放

                //获取 小 图片的相对路径 30*30 
                savePath = imgsrc.Replace("/temp/", "/small/");
                fileNmae = Server.MapPath(sHeaderPath);//物理存储路径

                if (!Directory.Exists(fileNmae))
                {
                    Directory.CreateDirectory(fileNmae);
                }
                ImageHelper.ZoomAuto(Server.MapPath(oSavePath), Server.MapPath(savePath), 30, 30, "", "");
            }
            catch (Exception e6)
            {
                //将异常信息存入SysLog日志表中 by lx 2015.1.20
                tmpLog.ILogType = 999;
                tmpLog.SMessage = savePath + "::::" + e6.Message.ToString();
                _logDao.Insert(tmpLog);
            }
           
            return;
        }


        /// <summary>
        /// office预览
        /// </summary>
        /// <param name="filePath">文件相对路径</param>
        /// <returns></returns>
        public string ShowOfficeDoc(string filePath)
        {
            bool officeInternetView = currentSys.isShowMS;//是否使用互联网在线预览
            string hostName = HttpUtility.UrlPathEncode(currentSys.SysURL);//可以配置一下，如果有必要
            string viewUrl;

            string ext = Path.GetExtension(filePath);//扩展名 “.doc"


            if (ext == ".xls" || ext == ".xlsx" || ext == ".doc" || ext == ".docx" || ext == ".ppt" || ext == ".pptx")
            {
                if (officeInternetView)
                {
                    //返回一个微软在线浏览Office的地址，需要加上互联网域名或者公网IP地址
                    viewUrl = string.Format("http://view.officeapps.live.com/op/view.aspx?src={0}{1}", hostName, filePath);
                }
                else
                {
                    string viewFile = filePath.Substring(0, filePath.LastIndexOf("/"));
                    string viewFilePath = viewFile.Replace("/UploadFile", "/ViewFile");

                    //返回路径供查看
                    string webPath = string.Format(viewFilePath + "/{0}.htm", Path.GetFileNameWithoutExtension(filePath));

                    viewUrl = webPath;//返回正确的路径
                }

            }
            else
            {
                viewUrl = filePath;
            }

            return viewUrl;
        }


        /// <summary>
        /// 首页单条公告
        /// </summary>
        /// <returns></returns>
        public JsonResult SearchNotice(int id)
        {

            TbNotices notice = new NoticesDAO().GetByID(id);
            string title = notice.STitle;
            string content = new NoticesContentDAO().findByINoticesId(id)[0].SContent;
            return Json(new { title = title, content = content });
        }
    }
}
